const express = require('express')
const router = express.Router()
const { announcementService } = require('../services')
const {
  authMiddleware,
  adminMiddleware,
  adminOrTrafficMiddleware,
} = require('../middlewares/authMiddleware')

// 获取所有公告（无需登录）
router.get('/', async (req, res) => {
  try {
    const announcements = await announcementService.getAllAnnouncements()
    res.status(200).json({
      success: true,
      data: announcements,
    })
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message || '获取公告失败',
      error: error.message,
    })
  }
})

// 创建公告（仅管理员或交通管理员）
router.post('/', authMiddleware, adminOrTrafficMiddleware, async (req, res) => {
  try {
    const announcementData = {
      content: req.body.content,
      publishTime: req.body.publishTime,
    }

    const newAnnouncement = await announcementService.createAnnouncement(
      announcementData
    )
    res.status(201).json({
      success: true,
      message: '公告创建成功',
      data: newAnnouncement,
    })
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message || '创建公告失败',
      error: error.message,
    })
  }
})

// 更新公告（仅管理员或交通管理员）
router.put(
  '/:id',
  authMiddleware,
  adminOrTrafficMiddleware,
  async (req, res) => {
    try {
      const announcementData = {
        content: req.body.content,
        publishTime: req.body.publishTime,
      }

      const updatedAnnouncement = await announcementService.updateAnnouncement(
        req.params.id,
        announcementData
      )
      res.status(200).json({
        success: true,
        message: '公告更新成功',
        data: updatedAnnouncement,
      })
    } catch (error) {
      res.status(400).json({
        success: false,
        message: error.message || '更新公告失败',
        error: error.message,
      })
    }
  }
)

// 删除公告（仅管理员或交通管理员）
router.delete(
  '/:id',
  authMiddleware,
  adminOrTrafficMiddleware,
  async (req, res) => {
    try {
      await announcementService.deleteAnnouncement(req.params.id)
      res.status(200).json({
        success: true,
        message: '公告删除成功',
      })
    } catch (error) {
      res.status(400).json({
        success: false,
        message: error.message || '删除公告失败',
        error: error.message,
      })
    }
  }
)

module.exports = router
